package cn.hchaojie.es;

import java.util.List;
import java.util.Optional;

import org.apache.lucene.search.WildcardQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import cn.hchaojie.elasticsearch.dao.ProductDao;
import cn.hchaojie.elasticsearch.domain.Product;

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:context.xml")
public class DemoEs {
	@Autowired
	ProductDao dao;
	
	@Test
	public void testAdd() {
		Product p = new Product(); 
		p.setId(1);
		p.setName("四星笔记本");
		p.setCategory("笔记本电脑");
		p.setCid(1);
		p.setPrice(9999D);
		
		dao.save(p);
	}
	
	@Test
	public void testQuery() {
		Iterable<Product> all = dao.findAll();
		for (Product p : all) {
			System.out.println(p);
		}
	}
	
	@Test
	public void testDelete() {
		dao.deleteById(3);
	}
	
	@Test
	public void testUpdate() {
		Optional<Product> optional = dao.findById(4);
		
		if (optional.isPresent()) {
			Product product = optional.get();
			product.setName("java项目开发");
			dao.save(product);
		}
	}
	
	@Test
	public void testFindOne() {
		Optional<Product> optional = dao.findById(4);
		System.out.println(optional.get());
	}
	
	@Test
	public void testOrder() {
		Sort sort = new Sort(Direction.ASC, "id");
		Iterable<Product> all = dao.findAll(sort);
		
		for (Product p : all) {
			System.out.println(p);
		}
	}
	
	@Test
	public void testPage() {
		Page<Product> page = dao.findAll(PageRequest.of(0, 5));
		
		System.out.println("当前第几页：" + page.getNumber());
		System.out.println("当前页多少条数据：" + page.getNumberOfElements());
		System.out.println("一共多少条数据：" + page.getTotalElements());
		System.out.println("一共多少页：" + page.getTotalPages());
		for (Product p : page.getContent()) {
			System.out.println(p);
		}
	}
	
	@Test
	public void prepareData() {
		for (int i = 20; i < 40; i++) {
			Product p = new Product(); 
			p.setId(i);
			p.setName("三星笔记本" + i);
			p.setCategory("笔记本电脑" + i);
			p.setCid(1);
			p.setPrice(9999D);
			
			dao.save(p);
		}
	}
	
	@Test
	public void testFindByName() {
//		List<Product> list = dao.findByProductName("笔记本");
		List<Product> list = dao.findByName("三星笔记本100");
//		List<Product> list = dao.findByCategory("笔记本");
//		List<Product> list = dao.findByNameAndCategory("笔记本", "java");
		//List<Product> list = dao.findByNameOrCategory("笔记本", "java");
		// List<Product> list = dao.findByPriceBetween(0, 200);
//		List<Product> list = dao.findByNameLike("笔");
		for (Product p : list) {
			System.out.println(p);
		}
	}
}
